package com.hbzjt2012.demo02;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

//线程创建方式三：实现callable接口
/*
callable的好处
1.可以定义返回值
2.可以抛出异常
 */
public class TestCallable implements Callable<Boolean> {
    private String url;     //网络图片地址
    private String name;    //保存的文件名

    public TestCallable(String url, String name){
        this.url = url;
        this.name = name;
    }

    //下载图片线程的执行体
    @Override
    public Boolean call() {
        WebDownloader webDownloader = new WebDownloader();
        webDownloader.downloader(url, name);
        System.out.println("下载的文件名为：" + name);
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        TestCallable t1 = new TestCallable("https://cdn.lixingyong.com/2021/10/28/t0194a1161f2ce1524e.jpg", "test1.jpg");
        TestCallable t2 = new TestCallable("https://cdn.lixingyong.com/2021/10/28/t01054da51d6beb507c.jpg", "test2.jpg");
        TestCallable t3 = new TestCallable("https://cdn.lixingyong.com/2021/10/28/t011163ac77ca558ca5.jpg", "test3.jpg");

        //创建线程服务
        ExecutorService ser = Executors.newFixedThreadPool(3);

        //提交执行
        Future<Boolean> result1 = ser.submit(t1);
        Future<Boolean> result2 = ser.submit(t2);
        Future<Boolean> result3 = ser.submit(t3);

        System.out.println(result1);
        System.out.println(result2);
        System.out.println(result3);

        //获取结果
        boolean rs1 = result1.get();
        boolean rs2 = result2.get();
        boolean rs3 = result3.get();

        //关闭服务
        ser.shutdown();
    }
}

//下载器
class WebDownloader{
    //下载方法
    public void downloader(String url, String name){
        try {
            FileUtils.copyURLToFile(new URL(url), new File(name));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("IO异常，downloader方法出现问题");
        }
    }
}
